﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace VentAnalyServer
{
    public class FileUtil
    {
        public static byte[] FileToBytes(string fileName)
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                byte[] bytes = StreamToBytes(fs);
                return bytes;
            }
            //FileStream fs = new FileStream(fileName, FileMode.Open);
            //byte[] bytes = StreamToBytes(fs);
            //fs.Close();
            //return bytes;
        }

        public static byte[] StreamToBytes(Stream stream)
        {
            using (BinaryReader br = new BinaryReader(stream))
            {
                byte[] bytes = br.ReadBytes((int)stream.Length);
                return bytes;
            }
            //BinaryReader br = new BinaryReader(stream);
            //byte[] bytes = br.ReadBytes((int)stream.Length);
            //br.Close();
            //return bytes;
        }

        public static void BytesToFile(byte[] bytes, string fileName)
        {
            using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
            {
                fs.Write(bytes, 0, bytes.Length);
            }
            //FileStream pFileStream = null;
            //try
            //{
            //    pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
            //    pFileStream.Write(bytes, 0, bytes.Length);
            //}
            //catch
            //{
            //}
            //finally
            //{
            //    if (pFileStream != null)
            //    {
            //        pFileStream.Close();
            //    }
            //}
        }

        // 修改文件扩展名
        // 注: 与原文件再同一路径下
        public static string BuildFileNameWithNewExtension(string inFile, string ext)
        {
            string dir = Path.GetDirectoryName(inFile);
            string filename = Path.GetFileNameWithoutExtension(inFile);
            string outFile = Path.Combine(dir, string.Format("{0}{1}", filename, ext));
            return outFile;
        }
    }
}
